
$(function() {
	
	total();
	
	var grid;
	var columns = [{
	    id: "#",
	    name: "",
	    width: 40,
	    behavior: "selectAndMove",
	    unselectable: true,
	    resizable: false,
	    cssClass: "cell-reorder"
	}, {
	    id: "date",
	    name: "日期",
	    field: "date",
	    width: 100,
	    cssClass: "cell-title",
	    editor: Slick.Editors.Date,
	    validator: requiredFieldValidator
	}, {
	    id: "name",
	    name: "备注",
	    field: "name",
	    width: 290,
	    cssClass: "cell-title",
	    editor: Slick.Editors.Text,
	    validator: requiredFieldValidator
	}, {
	    id: "amount",
	    name: "数量",
	    field: "amount",
	    width: 100,
	    cssClass: "cell-title",
	    editor: Slick.Editors.Text,
	    validator: requiredFieldValidator
	}, {
	    id: "ok",
	    name: "",
	    field: "ok",
	    width: 80,
	    cssClass: "cell-effort-driven",	    
	    cannotTriggerInsert: true,
	    formatter: Slick.Formatters.YesNo,
	    editor: Slick.Editors.Checkbox
	}];

	var options = {
			editable: true,
		    enableAddRow: true,
		    enableCellNavigation: true,
		    asyncEditorLoading: false,
		    rowHeight: 30
		};	
	
	grid = new Slick.Grid($("#myGrid"), data, columns, options);
	
	grid.onAddNewRow.subscribe(function (e, args) {
	// grid.onAddNewRow = function addItem(newItem,columnDef) {
		var item = {date:"", name:"", amount:"0", ok: true};
       item.date = current_date();
        
       $.extend(item, args.item);
       data.push(item);
       grid.invalidateRows([data.length - 1]);
       grid.updateRowCount();
       grid.render();
        
       total();
    });
    
	grid.onCellChange.subscribe(function(e, args) {
    // grid.onCellChange = function(currentRow, currentCell, item) {
		
		item = args.item;
		
    	total();
    });
});

function total() {
	var total = 0;
	$.each(data, function(k, v) {
		if (v.ok) {
			total += parseFloat(v.amount);
		}		
	});
		
	$("#total_t").html(total);
	$("#total").val(total);
}
